/*
 * 智能测肤的折线图组件
 * @Author:ljb
 * @Date: 2018-05-09 15:17:36
 * @Last Modified by: ljb
 * @Last Modified time: 2019-01-08 15:30:21
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
@import "~src/assets/css/common.less";

.line-chart {
  width: 100%;
  height: 5rem;
  margin-top: 20 * @rem-per-px;
}
</style>
<template>
  <div id="line_chart" ref="line_chart" class="line-chart"/>
</template>

<script>
import echarts from "echarts";

export default {
  name: "LineChartComponent",
  props: {
    chartData: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      max_value_map: {
        water: 100,
        oil: 50,
        flex: 10
      },

      color_map: {
        water: "rgba(33,152,253)",

        oil: "rgb(254,173,47)",

        flex: "rgb(255,115,141)"
      },

      line_chart: null,

      x: 0, // 图表的tooltip的x轴坐标

      y: 0 // 图表的tooltip的x轴坐标
    };
  },
  watch: {
    chartData() {
      this.initChartData();
    }
  },
  mounted() {
    this.line_chart = echarts.init(this.$refs.line_chart);

    this.initChartData();
  },
  beforeDestroy() {
    this.line_chart.dispose();
  },
  methods: {
    /**
     * 初始化折线图data
     * @return {undefined}
     */
    initChartData() {
      if (this.chartData.length === 0) return;

      const need_data = ["water", "oil", "flex"];

      this.formatData(need_data);
    },

    /**
     * 设置echarts
     * @param  {Array} xAxis  {x轴}
     * @param  {Array} series {数据}
     * @return {undefined}
     */
    setEchartOption({ legend_data, grid, xAxis, yAxis, series, dataZoom }) {
      const self = this;

      this.line_chart.clear();

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            axis: "x",
            label: {
              show: true,
              color: "#FFBED6",
              backgroundColor: "none",
              formatter(params) {
                const date = params.value
                  .split(" ")
                  .shift()
                  .split("-");

                return `${date[1]}-${date[2]}`;
              }
            }
          },
          position(point, param) {
            if (self.x !== point[0] || self.y !== point[1]) {
              [self.x, self.y] = point;

              self.$emit("show", param[0].name);
            }
          }
        },
        legend: {
          //折线数据表头设置
          selectedMode: false,
          data: legend_data,
          x: "left",
          textStyle: {
            fontSize: 9
          },
          itemWidth: 6,
          itemHeight: 6
        },

        dataZoom: [
          {
            // 这个dataZoom组件，也控制x轴。 
            type: "inside", // 这个 dataZoom 组件是 inside 型 dataZoom 组件
            realtime: true,
            start: 100 - dataZoom,
            end: 100,
            zoomLock: true,
            xAxisIndex: [0, 1, 2]
          }
        ],
        grid,
        xAxis,
        yAxis,
        series
      };

      this.line_chart.setOption(option);

      this.$emit("show", this.chartData[this.chartData.length - 1].created_at);
    },

    /**
     * 格式化数据成echart配置项所需数据
     * @param  {Array} need_data {需要展示的数据}
     * @return {undefined}
     */
    formatData(need_data) {
      const chart_option = {
        legend_data: [],

        grid: [],

        xAxis: [],

        yAxis: [],

        series: [],

        dataZoom: 5
      };

      const self = this;

      const device_width = window.innerWidth;

      const data_length = this.chartData.length;

      chart_option.dataZoom =
        (parseFloat((device_width / 70).toFixed(2)) * 100) / data_length; // 根据屏幕宽度计算显示的条目数

      need_data.forEach((data, index) => {
        const grid_option = {
          left: 0,
          right: 0,
          top: 50
          // height: '40%',
        };

        chart_option.grid.push(grid_option);

        self.assembleData(chart_option, data, index);
      });

      this.setEchartOption(chart_option);
    },

    /**
     * 组装数据
     * @param  {Object} option      {echart配置项对象}
     * @param  {string} data_type       {当前需要取测肤数据类型的类型，water，oil，flex}
     * @param  {number} array_index {测肤数据类型在数组的index}
     * @return {undefined}
     */
    assembleData(option, data_type, array_index) {
      const self = this;

      let series_name = "";

      const xAxis_data = [];

      const series_data = [];

      switch (data_type) {
        case "water":
          series_name = `${this.$t("report.water")}`; // （%）水分

          self.chartData.forEach(({ water, created_at }) => {
            series_data.push(`${Number(water)}`);

            xAxis_data.push(`${created_at}`);
          });

          break;

        case "oil":
          series_name = `${this.$t("report.oil")}`; // （%）油分

          self.chartData.forEach(({ oil, created_at }) => {
            series_data.push(`${Number(oil)}`);

            xAxis_data.push(`${created_at}`);
          });

          break;

        default:
          series_name = `${this.$t("report.elastic")}`; // '弹性';

          self.chartData.forEach(({ flex, created_at }) => {
            series_data.push(`${Number(flex)}`);

            xAxis_data.push(`${created_at}`);
          });

          break;
      }

      // 配置显示的数据
      const series = {
        xAxisIndex: array_index,
        yAxisIndex: array_index,
        name: series_name,
        type: "line",
        symbol: "circle",
        symbolSize: 8,
        hoverAnimation: false,
        silent: true,
        itemStyle: {
          color: self.color_map[data_type]
        },
        lineStyle: {
          color: self.color_map[data_type]
        },

        data: series_data
      };

      // 配置x轴数据
      const xAxis = {
        show: array_index === 0,
        gridIndex: array_index,
        type: "category",
        axisLine: {
          onZero: true,
          lineStyle: {
            //横坐标直线的颜色
            color: "#FFBED6"
            // backgroundColor:'red'
          }
        },
        data: xAxis_data,
        axisTick: {
          interval: 0,
          alignWithLabel: true
        },
        axisPointer: {
          snap: true,
          lineStyle: {
            color: "#FFAECC"
          },
          link: {
            xAxisIndex: "all"
          },
          handle: {
            show: true,
            color: "#fff",
            size: [0, 0]
          }
        },
        axisLabel: {
          //横坐标数据显示的颜色
          interval: 0,
          color: "#333",
          formatter(value) {
            const date = value
              .split(" ")
              .shift()
              .split("-");

            return `${date[1]}-${date[2]}`;
          }
        }
      };

      // 配置y轴数据
      const yAxis = {
        gridIndex: array_index,
        show: false,
        name: series_name,
        type: "value",
        max: this.max_value_map[data_type],
        splitLine: {
          show: false
        }
      };

      option.legend_data.push({
        name: series_name,
        icon: "circle"
      });
      option.xAxis.push(xAxis);
      option.yAxis.push(yAxis);
      option.series.push(series);
    }
  }
};
</script>
